package com.itxiuyixiu.tools.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.annotation.Resource;

/**
 * @author 黄磊
 * @date 2020/5/7
 */
public class SimpleEmailService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public boolean sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        for (int i = 0; i < 5; i++) {
            try {
                mailSender.send(message);
                logger.trace("发给" + to + "的邮件已经发送");
                return true;
            } catch (Exception e) {
                logger.error("发给" + to + "的邮件时发生异常！", e);
            }
        }
        return false;
    }
}
